package com.credithc.customers.dataservice.service.impl;

import com.credithc.customers.base.mapper.DictMapperMapper;
import com.credithc.customers.base.po.DictMapperPo;
import com.credithc.customers.dataservice.service.InitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhukai
 * @date 2019/1/15 16:46
 */
@Service
public class InitServiceImpl implements InitService {

    private final DictMapperMapper dictMapperMapper;

    @Autowired
    public InitServiceImpl(DictMapperMapper dictMapperMapper) {
        this.dictMapperMapper = dictMapperMapper;
    }

    private static Map<String, Map<String,Map<String,String>>> dictMapperMap = new HashMap<>();

    @Override
    public void cacheDictMapper() {
        List<DictMapperPo> list = dictMapperMapper.selectAll();
        Map<String,Map<String,String>> systemMap;
        Map<String, String> valueMap;
        for(DictMapperPo po : list){
            String mapperType = po.getMapperType().split("_")[1];
            String systemSign = po.getSystemSign();
            String code = po.getCode();
            String dictCode = po.getDictCode().split("_")[1];
            if(!dictMapperMap.containsKey(mapperType)){
                valueMap = new HashMap<>();
                valueMap.put(code,dictCode);
                systemMap = new HashMap<>();
                systemMap.put(systemSign,valueMap);
            }else{
                systemMap = dictMapperMap.get(mapperType);
                if(!systemMap.containsKey(systemSign)){
                    systemMap = new HashMap<>();
                    valueMap = new HashMap<>();
                    valueMap.put(code,dictCode);
                }else{
                    valueMap = systemMap.get(systemSign);
                    valueMap.put(code,dictCode);
                }
                systemMap.put(systemSign,valueMap);
            }
            dictMapperMap.put(mapperType, systemMap);
        }
    }

    @Override
    public void clearDictMapperCache() {
        dictMapperMap.clear();
    }

    @Override
    public String getDictMapper(String code, String systemSign, String type) {
        if(dictMapperMap.containsKey(type)){
            Map<String, Map<String, String>> systemMap = dictMapperMap.get(type);
            if(systemMap != null && systemMap.containsKey(systemSign)){
                Map<String, String> valueMap = systemMap.get(systemSign);
                if(valueMap != null && valueMap.containsKey(code)){
                    return valueMap.get(code);
                }
            }
        }
        return null;
    }
}
